#include "ilcontainer.h"

ILContainer::ILContainer()
{
	this->il_handle = (ILint) -1;
	this->il_texture_handle = (ILint) -1;
}

ILContainer::~ILContainer()
{
	this->TakeDown();
}

bool ILContainer::Initialize(const char * filename)
{
	il_handle = ilGenImage();

	if (il_handle == (ILint) -1)
	{
		return false;
	}

	// reference: http://www-f9.ijs.si/~matevz/docs/DevIL/il/f00013.htm
	ilBindImage(this->il_handle);

	// reference: http://www-f9.ijs.si/~matevz/docs/DevIL/il/f00039.htm
	if (!ilLoadImage(filename))
	{
		return false;
	}

	glGenTextures(1, &this->il_texture_handle);
	glBindTexture(GL_TEXTURE_2D, this->il_texture_handle);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	// reference: http://www-f9.ijs.si/~matevz/docs/DevIL/il/f00027.htm
	width = ilGetInteger(IL_IMAGE_WIDTH);
	height = ilGetInteger(IL_IMAGE_HEIGHT);

	// reference: http://www-f9.ijs.si/~matevz/docs/DevIL/il/f00125.htm
	glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), width, height, 0,
				 ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());
	
	return true;
}

void ILContainer::TakeDown()
{
	if (this->il_texture_handle != (ILint) -1)
	{
		glDeleteTextures(1, &this->il_texture_handle);
	}

	if (this->il_handle != (ILint) -1)
	{
		ilDeleteImage(this->il_handle);
	}

	this->il_handle = (ILint) -1;
	this->il_texture_handle = (ILint) -1;
}

void ILContainer::Bind(GLuint texture_unit)
{
	// reference: http://www.opengl.org/sdk/docs/man/xhtml/glActiveTexture.xml
	glActiveTexture(GL_TEXTURE0 + texture_unit);
	glBindTexture(GL_TEXTURE_2D, this->il_texture_handle);
}